import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : zhangliang
 * @date : 2023-11-21
 */
public class PicToXlsx {

    static int num;

    static void create(List<int[]> list, String path) throws Exception {
        long a = System.currentTimeMillis();
        // 先保存一个空Excel文件，在磁盘占位
        XSSFWorkbook excel = new XSSFWorkbook();
        excel.createSheet("myPic");
        path = saveExcel(path, excel);

        int length = list.get(0).length;

        // 读取占位的文件，设置列宽
        System.out.println("Start setting the style of cells…");
        excel = new XSSFWorkbook(new FileInputStream(path));
        XSSFSheet sht = excel.getSheetAt(0);
        for (int j = 0; j < length; j++) {
            sht.setColumnWidth(j, (short) 500);
        }

        // 缓存所需的所有单元格格式
        XSSFCellStyle xstyle = excel.createCellStyle();
        int size = list.size();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        //多线程
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        for (int i = 0; i < list.size(); i++) {
            final int index = i;
            executorService.execute(() -> {
                Row row = sht.createRow(index);
                // 设置行高，使之与列宽相等（即：设置单元格为正方形）
                row.setHeight((short) 250);
                for (int j = 0; j < list.get(index).length; j++) {
                    XSSFCellStyle style = (XSSFCellStyle) xstyle.clone();
                    style.setFillForegroundColor(new XSSFColor(new Color(list.get(index)[j])));
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    row.createCell(j).setCellStyle(style);
//                System.out.println("j: " + j);
                }
                System.out.println("i: " + index + "  num:" + num++ + "  time:" + new Date().toLocaleString());
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        saveExcel(path, excel);
        long b = System.currentTimeMillis();
        System.out.println("Done");// 提示完成
        System.out.println((b - a) / 1000 + "s");
    }

    private static String saveExcel(final String path, XSSFWorkbook excel) throws Exception {
        try {
            FileOutputStream out = new FileOutputStream(path);
            excel.write(out);
//			excel.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            throw new Exception("Cannot write an excel file to disk.", e);
        }
        return path;
    }

}